package sk.tramtatiri.pages.users;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import sk.tramtatiri.MySession;
import sk.tramtatiri.core.IConstants;

//import sk.mucha.tracking.Login.LoginForm;

/**
 * Homepage
 */
public class LoginPage extends UserPageTemplate {

	private String userEmail;
	private String password;

	/**
	 * Constructor that is invoked when page is invoked without a session.
	 * 
	 * @param parameters
	 *            Page parameters
	 */
	public LoginPage(final PageParameters parameters) {
		/**
		 * The first parameter to all Wicket component constructors is the same
		 * as the ID that is used in the template
		 */
		TextField userEmailField = new TextField("userEmail", new PropertyModel(this,"userEmail"));
		PasswordTextField passField = new PasswordTextField("password", new PropertyModel(this,"password"));
		/* Make sure that password field shows up during page re-render * */
		passField.setResetPassword(false);
		userEmailField.setRequired(true);
		passField.setRequired(true);
		
		Form< ? > form = new Form<Void>("loginForm") {
			
			@Override
			protected void onSubmit() {
				login();
//				info("Form successfully submitted");
			}
			
		};
		
		add(form);
		
		form.add(userEmailField);
		form.add(passField);
		add(new FeedbackPanel("loginFeedback"));
		add(new Link("registerLink") {

			@Override
			public void onClick() {
				setResponsePage(RegistrationPage.class);
			}
			
		});
	}

	private void login() {
		MySession session = (MySession)getSession();
		if (session.login(this.userEmail, this.password)) {
			if (!continueToOriginalDestination()) {
				setResponsePage(getApplication().getHomePage());
			}
		} else {
			error(getString("message_login_unsuccessful"));
		}
	}
	
	/** Helper methods to retrieve the userId and the password **/
	public String getUserEmail() {
		return userEmail;
	}

	public String getPassword() {
		return password;
	}

	@Override
	public String getPageTitle() {
		return IConstants.PAGE_NAME+" - Prihlasenie";
	}
	
}
